﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MashGen.Engine.Expressions;

namespace MashGen.Engine.Matching
{
    internal class Builder
    {
        private List<Attempt> attempts;
        private List<Match> successfullMatches;
        private AbstractExpression pattern;

        public Builder(AbstractExpression pattern)
        {
            attempts = new List<Attempt>();
            successfullMatches = new List<Match>();
            this.pattern = pattern;
        }

        public void AddNewAttempt(AbstractExpression root)
        {
            // Only start an attempt if there is at least a chance
            // for a match. This is the pattern is just a variable 
            // or when it has the same type as the expression 
            // (numbers can onl match numbers, sums can only match
            // sums, etc.)
            var patternType = pattern.GetType();
            if (patternType == typeof(Variable)
                || patternType == root.GetType())
            {
                attempts.Add(new Attempt(this, pattern, root));
            }
        }

        public void DoForEach(Action<Attempt> action)
        {
            attempts.ForEach(action);
        }

        public void AttemptFailed(Attempt attempt)
        {
            attempts.Remove(attempt);
        }

        public void AttemptSucceeded(Attempt attempt)
        {
            successfullMatches.Add(attempt.Match);
            attempts.Remove(attempt);
        }

        public List<Match> SuccessfullMatches
        {
            get { return successfullMatches; }
        }
    }
}
